﻿Imports NVelocity
Imports NVelocity.App
Imports NVelocity.Context

Imports System.Collections.Generic
Imports System.IO

Imports System.Data
Imports System.Data.SqlClient

Partial Class WebForm_ManageWorkRecord_AddCleanPlan
    Inherits My.MyUserControl
#Region "事件"
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.fv.InsertItemTemplate = Me.fv.EditItemTemplate
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnExport)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnSave)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnApprove)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnUploadFile)
        btnSave.Attributes("onclick") = "this.disabled=true;" & Me.Page.ClientScript.GetPostBackEventReference(btnSave, "")
        btnApprove.Attributes.Add("onclick", "this.disabled=true; if(confirm('確定審核?')){" & Page.ClientScript.GetPostBackEventReference(btnApprove, "").ToString() & "} else{this.disabled = false;return false;}")
    End Sub
    '刪除
    Protected Sub chkAlldelete_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_Volunteers.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkdelete"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
    '簽到
    Protected Sub chkAllSignIn_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_Volunteers.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignIn"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
    '簽退
    Protected Sub chkAllSignOut_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_Volunteers.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignOut"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub


    '開窗取值-Volunteer
    Protected Sub btnShowPerson_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowPerson.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData


        ' Me.GridView_Volunteers.DataSourceID = "ObjectDataSource_Volunteers"
        Using scope As New Transactions.TransactionScope
            If DataAccessMode = FormDataAccessMode.Take And Me.WorkHeaderID = 0 Then

                sql.Length = 0
                sql.AppendFormat("Insert Into WorkHeader(CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT getdate(),'{0}' ", Me.Page.User.Identity.Name)
                dat.AccData(sql)
                WorkHeaderID = MyObj.GetIdentity()

            End If
            scope.Complete()
        End Using
        SearchVolunteerControl_AddCleanPlan1.WorkHeaderID = WorkHeaderID
        SearchVolunteerControl_AddCleanPlan1.InitDataAndShow()

    End Sub

    '開窗取值回來-Volunteer
    Protected Sub SearchVolunteerControl1_OK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchVolunteerControl_AddCleanPlan1.OK_Click

        Me.SavePerson()
        Me.BindGV()
        'GridView_Volunteers.DataBind()

    End Sub

    Protected Sub fv_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
        TryCast(Me.fv.FindControl("SelfRegionType1"), WebForm_ManageWorkContent_vSelfRegionType).BindgvRegionType()

        If Me.fv.CurrentMode = FormViewMode.Edit Then
            TryCast(Me.fv.FindControl("SelfRegionType1"), WebForm_ManageWorkContent_vSelfRegionType).BindRegionItem(Me.PlanID, DataBinder.Eval(Me.fv.DataItem, "RegionType").ToString())
            TryCast(Me.fv.FindControl("SelfRegionType1"), WebForm_ManageWorkContent_vSelfRegionType).ResetLink = False
            'ResetLink
            TryCast(fv.FindControl("chkPublic"), CheckBox).Checked = MyConvert.ToDBBoolean(DataBinder.Eval(Me.fv.DataItem, "IsPublic")).Value
        End If

    End Sub
    '審核
    Protected Sub btnApprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApprove.Click
        Me.Approved = True
        Me.btnSave_Click(Nothing, Nothing)
    End Sub
    Protected Sub GridView_Volunteers_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_Volunteers.DataBound
        If Me.DataAccessMode = FormDataAccessMode.Take Then
            '隱藏時數
            '隱藏簽到狀態
            Me.GridView_Volunteers.Columns(3).Visible = False
            ' Me.GridView_Volunteers.Columns(5).Visible = False
            Me.GridView_Volunteers.Columns(Me.GridView_Volunteers.Columns.Count - 2).Visible = False
            Me.GridView_Volunteers.Columns(Me.GridView_Volunteers.Columns.Count - 3).Visible = False
        Else
            Me.GridView_Volunteers.Columns(3).Visible = True
            ' Me.GridView_Volunteers.Columns(5).Visible = False
            Me.GridView_Volunteers.Columns(Me.GridView_Volunteers.Columns.Count - 2).Visible = True
            Me.GridView_Volunteers.Columns(Me.GridView_Volunteers.Columns.Count - 3).Visible = True
        End If

    End Sub

    'GridView_Volunteers-更新
    'Protected Sub GridView_Volunteers_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView_Volunteers.RowUpdating
    '    e.NewValues("LoginUser") = Page.User.Identity.Name
    'End Sub

    'Protected Sub GridView_Volunteers_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles GridView_Volunteers.RowUpdated
    '    MyObj.ShowMessage(Me.GetLocalResourceObject("UpdateSuccess"))
    'End Sub
    '上傳檔案
    Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadFile.Click
        Me.UploadFileControl1.IsColse = False
        UploadFileControl1.InitDataAndShow()
    End Sub

    '查詢
    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click

        'GridView_Volunteers.DataSourceID = "ObjectDataSource_Volunteers"
        'GridView_Volunteers.DataBind()
        Me.BindGV()
    End Sub
    '顯示總筆數
    'Protected Sub ObjectDataSource_Volunteers_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles ObjectDataSource_Volunteers.Selected
    '    Dim Count As Integer = DirectCast(e.ReturnValue, DataTable).Rows.Count
    '    If Count > 0 Then
    '        Me.lblTotal.Text = Count & Space(1) & "records"
    '    Else
    '        Me.lblTotal.Text = ""
    '    End If
    'End Sub

    'Protected Sub ObjectDataSource_Volunteers_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) Handles ObjectDataSource_Volunteers.Selecting
    '    ObjectDataSource_Volunteers.SelectParameters.Item("WorkHeaderID").DefaultValue = WorkHeaderID
    '    ObjectDataSource_Volunteers.SelectParameters.Item("UOrganizationID").DefaultValue = VolunteerQueryControl1.OrganizationID
    '    ObjectDataSource_Volunteers.SelectParameters.Item("VOrganizationID").DefaultValue = VolunteerQueryControl1.VOrganizationID
    '    ObjectDataSource_Volunteers.SelectParameters.Item("VolunteerId").DefaultValue = VolunteerQueryControl1.VolunteerId
    '    ObjectDataSource_Volunteers.SelectParameters.Item("VolunteerName").DefaultValue = VolunteerQueryControl1.VolunteerName
    '    ObjectDataSource_Volunteers.SelectParameters.Item("TEL").DefaultValue = VolunteerQueryControl1.VolunteerTEL
    'End Sub

    '繫結計畫內容
    Protected Sub BindPlanContent(ByVal PlanID As String)
        Me.fv.ChangeMode(FormViewMode.Edit)

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("Select c.PlanName,c.UOrganizationID,c.PersonInCharge ")
        sql.AppendFormat(",c.OrganizationTel,c.Location,c.StartDate,c.EndDate ")
        sql.AppendFormat(",o.OrganizationName ")
        sql.AppendFormat("From CleanPlan c Left Outer join OrganizationView o ")
        sql.AppendFormat("on c.UOrganizationID = o.UOrganizationID ")
        sql.AppendFormat("Where c.PlanID='{0}'", PlanID)

        Me.fv.DataSource = dat.GetData(sql)
        Me.fv.DataBind()
    End Sub

    Protected Sub GridView_Volunteers_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView_Volunteers.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim chkSignIn As CheckBox = TryCast(e.Row.FindControl("chkSignIn"), CheckBox)
            Dim chkSignOut As CheckBox = TryCast(e.Row.FindControl("chkSignOut"), CheckBox)

            Dim CheckStatus As Integer = DataBinder.Eval(e.Row.DataItem, "Status").ToString()



            Select Case CheckStatus
                Case 1
                    chkSignIn.Checked = True
                    chkSignOut.Checked = False
                Case 2
                    chkSignIn.Checked = False
                    chkSignOut.Checked = True
                Case 3
                    chkSignIn.Checked = True
                    chkSignOut.Checked = True
                Case Else
                    chkSignIn.Checked = False
                    chkSignOut.Checked = False
            End Select

            Dim chkAllSignIn As CheckBox = TryCast(Me.GridView_Volunteers.HeaderRow.FindControl("chkAllSignIn"), CheckBox)
            Dim chkAllSignOut As CheckBox = TryCast(Me.GridView_Volunteers.HeaderRow.FindControl("chkAllSignOut"), CheckBox)

            chkAllSignIn.Checked = chkAllSignIn.Checked And chkSignIn.Checked
            chkAllSignOut.Checked = chkAllSignOut.Checked And chkSignOut.Checked
        End If
    End Sub
    '套用時數
    Protected Sub btnUpdateHour_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateHour.Click
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Using scope As New Transactions.TransactionScope
            sql.AppendFormat("update whr set WorkHour = @WorkHour ")
            sql.AppendFormat("from WorkHourRecord whr ")
            sql.AppendFormat("inner join WorkRecord wr on whr.RecordID = wr.RecordID and whr.WorkType = @WorkType ")
            sql.AppendFormat("inner join WorkHeader wh on wr.WorkHeaderID = wh.WorkHeaderID ")
            sql.AppendFormat(" Where wh.WorkHeaderID = @WorkHeaderID ")

            sql.AddWithValue("WorkType", "CleanPlan")
            sql.AddWithValue("WorkHour", Integer.Parse(Me.txtDefaultWorkHour.Text))
            sql.AddWithValue("WorkHeaderID", Me.WorkHeaderID)

            dat.AccData(sql)

            scope.Complete()
        End Using

        Me.BindGV()
    End Sub
#End Region

#Region "存檔"

    Public Event Save_Click(ByVal source As Object, ByVal e As EventArgs)

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Me.UOrganizationID = TryCast(Me.fv.FindControl("txtOrganizationID"), TextBox).Text
        Me.VOrganizationID = Me.AddLeader1.VOrganizationID
        If Page.IsValid = False Then
            Return
        End If

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim i As Integer

        Dim MyWorkHeaderID As Integer

        Dim FormView_WorkHeader As FormView
        Dim startHour As Integer
        Dim EndHour As Integer
        Dim workStartDate As Date
        Dim workEndDate As Date

        If Me.DataAccessMode <> FormDataAccessMode.Take Then
            FormView_WorkHeader = AddWorkHeaderControl1.FindControl("FormView_WorkHeader")

            startHour = CInt(TryCast(FormView_WorkHeader.FindControl("SelectTimeStart"), WebForm_ReserveCar_SelectTime).Text)
            EndHour = CInt(TryCast(FormView_WorkHeader.FindControl("SelectTimeEnd"), WebForm_ReserveCar_SelectTime).Text)

            If startHour = 24 Then
                startHour = 0
            End If

            If EndHour = 24 Then
                EndHour = 0
            End If

            workStartDate = TryCast(FormView_WorkHeader.FindControl("txtWorkStartDate"), WebForm_CommonControl_CalendarTextBox).Value.AddHours(startHour)
            workEndDate = TryCast(FormView_WorkHeader.FindControl("txtWorkStartDate"), WebForm_CommonControl_CalendarTextBox).Value.AddHours(EndHour)
            '
            If Me.AddLeader1.TakeDate > workStartDate Then
                MyObj.ShowMessage("清潔日期不可小於認養日期")
                Return
            End If
            '認養日期不能超過關帳日
            If Me.CanAdmin = False AndAlso clsAuth.IsInCloseDate(workStartDate, workEndDate, Me.AddLeader1.TakeDate) = False Then
                MyObj.ShowMessage("已過關帳日")
                Return
            End If
            
        End If


        Using scope As New Transactions.TransactionScope

            If DataAccessMode = FormDataAccessMode.Take Then
                '存檔-WorkHeader
                If WorkHeaderID <> 0 Then
                    sql.AppendFormat("UPdate WorkHeader Set ")
                    sql.AppendFormat("CreateType='{0}' ", "P")
                    sql.AppendFormat(",UOrganizationID='{0}' ", Me.AddLeader1.UOrganizationID)
                    sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddLeader1.VOrganizationID)
                    sql.AppendFormat(",LeaderID='{0}' ", Me.AddLeader1.VolunteerID)
                    sql.AppendFormat(",CreateDate=getdate() ")
                    sql.AppendFormat(",CreateBy='{0}' ", clsAuth.GetUserID())
                    sql.AppendFormat(",TakeDate='{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                    sql.AppendFormat(",Active='{0}' ", "N")
                    sql.AppendFormat("Where WorkHeaderID='{0}' ", WorkHeaderID)
                Else
                    sql.AppendFormat("INSERT WorkHeader (CreateType,UOrganizationID,VUOrganizationID,LeaderID,CreateDate,CreateBy,TakeDate,Active) ")
                    sql.AppendFormat("SELECT 'P' ")
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.UOrganizationID)
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.VOrganizationID)
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.VolunteerID)

                    sql.AppendFormat(", getdate()")
                    sql.AppendFormat(", '{0}' ", Page.User.Identity.Name)
                    sql.AppendFormat(", '{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                    sql.AppendFormat(", '{0}'; ", "N")

                End If

                dat.AccData(sql)


                '將清潔內容新增到到WorlItem
                '步驟一:先將該服務計畫底下的清潔內容刪除
                '步驟二:再將清潔內容新增到 WorkItem
                'sql.Length = 0
                'sql.AppendFormat("delete from workitem where workHeaderID='{0}';", MyWorkHeaderID)
                'dat.AccData(sql)

                'Dim workitem As DataTable = Me.AddWorkItemControl1.GetWorkItem()
                'For k As Integer = 0 To workitem.Rows.Count - 1
                '    sql.Length = 0
                '    sql.AppendFormat("Insert workItem(WorkHeaderID,ItemGroupID,ItemID,Amount) ")
                '    sql.AppendFormat("Select '{0}' ", MyWorkHeaderID)
                '    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemGroupID").ToString)
                '    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemID").ToString)
                '    sql.AppendFormat(",'{0}' ;", workitem.Rows(k)("Amount").ToString())

                '    'dat.AccData(sql)
                'Next

                '將服務計畫加到某計畫底下
                sql.Length = 0

                'MyWorkHeaderID是local變數
                If WorkHeaderID = 0 Then
                    Me.WorkHeaderID = MyObj.GetIdentity()
                End If
                MyWorkHeaderID = Me.WorkHeaderID
            
                sql.AppendFormat("INSERT CleanPlanMapping (PlanID,WorkHeaderID) ")
                sql.AppendFormat("SELECT '{0}',{1} ", PlanID, MyWorkHeaderID)
                sql.AppendFormat("where not exists (Select * from CleanPlanMapping ")
                sql.AppendFormat("where PlanID='{0}' ", PlanID)
                sql.AppendFormat("and WorkHeaderID={0} ", MyWorkHeaderID)
                sql.AppendFormat("); ")
                'sql.AppendFormat("UPDATE WorkRecord ")
                'sql.AppendFormat("SET WorkHeaderID = '{0}' ", MyWorkHeaderID)
                'sql.AppendFormat("WHERE WorkHeaderID = 0 and CreateBy='{0}';", Page.User.Identity.Name)


                'sql.AppendFormat("UPDATE UploadFiles ")
                'sql.AppendFormat("SET theType = '{0}' ", MyWorkHeaderID)
                'sql.AppendFormat("WHERE theType = '0' and CreateBy='{0}';", Page.User.Identity.Name)

                '儲存處理前後照片

                'Me.AddWorkHeaderControl1.WorkHeaderID = Me.WorkHeaderID
                'Me.AddWorkHeaderControl1.SavePhoto()

                'sql.AppendFormat("UPDATE WorkHeader set ")
                'sql.AppendFormat("PreExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PreExecutionPhotoName)
                'sql.AppendFormat(",PostExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PostExecutionPhotoName)
                'sql.AppendFormat("WHERE WorkHeaderID = '{0}';", Me.WorkHeaderID)
            Else
                '存檔-WorkHeader
                sql.Length = 0
                sql.AppendFormat("UPDATE CleanPlanMapping ")
                sql.AppendFormat("SET PlanID={0} ", PlanID)
                sql.AppendFormat("WHERE WorkHeaderID={0};", WorkHeaderID)

                sql.AppendFormat("UPDATE WorkHeader ")
                'sql.AppendFormat("SET UOrganizationID='{0}' ", Me.AddWorkHeaderControl1.UOrganizationID)
                'sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddWorkHeaderControl1.VOrganizationID)
                'sql.AppendFormat(",LeaderID='{0}' ", Me.AddWorkHeaderControl1.VolunteerID)
                sql.AppendFormat("SET UOrganizationID='{0}' ", Me.AddLeader1.UOrganizationID)
                sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddLeader1.VOrganizationID)
                sql.AppendFormat(",LeaderID='{0}' ", Me.AddLeader1.VolunteerID)
                sql.AppendFormat(",PeopleJoined='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtPeopleJoined"), TextBox).Text)
                sql.AppendFormat(",WorkStartDate='{0:yyyy/MM/dd HH:mm} ' ", workStartDate)
                sql.AppendFormat(",WorkEndDate='{0:yyyy/MM/dd HH:mm}' ", workEndDate)
                sql.AppendFormat(",WorkHour='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtWorkHour"), TextBox).Text)
                sql.AppendFormat(",Active='{0}'", IIf(Me.Approved = True, "Y", "N"))

                '判斷是否選擇其他
                If TryCast(FormView_WorkHeader.FindControl("rbListCleanPeopleType"), RadioButtonList).SelectedItem.Text = "其他" Then
                    sql.AppendFormat(",CleanPeopleType='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtOther"), TextBox).Text)
                Else
                    sql.AppendFormat(",CleanPeopleType='{0}' ", TryCast(FormView_WorkHeader.FindControl("rbListCleanPeopleType"), RadioButtonList).SelectedItem.Text)
                End If

                'sql.AppendFormat(",CleanPeopleType='{0}' ", TryCast(FormView_WorkHeader.FindControl("rbListCleanPeopleType"), RadioButtonList).SelectedItem.Text)
                sql.AppendFormat(",UpdateDate=getdate() ")
                sql.AppendFormat(",UpdateBy='{0}' ", Page.User.Identity.Name)

                sql.AppendFormat("WHERE WorkHeaderID='{0}';", WorkHeaderID)


                MyWorkHeaderID = WorkHeaderID

                '修改清潔內容
                '步驟一:先將該服務計畫底下的清潔內容刪除
                '步驟二:再將清潔內容新增到 WorkItem
                'sql.AppendFormat("delete from workitem where workHeaderID='{0}';", MyWorkHeaderID)
                'dat.AccData(sql)

                'Dim workitem As DataTable = Me.AddWorkItemControl1.GetWorkItem()
                'For k As Integer = 0 To workitem.Rows.Count - 1
                '    sql.Length = 0
                '    sql.AppendFormat("Insert workItem(WorkHeaderID,ItemGroupID,ItemID,Amount) ")
                '    sql.AppendFormat("Select '{0}' ", MyWorkHeaderID)
                '    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemGroupID").ToString)
                '    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemID").ToString)
                '    sql.AppendFormat(",'{0}';", workitem.Rows(k)("Amount").ToString())

                '    'dat.AccData(sql)
                'Next

                '儲存處理前後照片

                'Me.AddWorkHeaderControl1.WorkHeaderID = Me.WorkHeaderID
                'Me.AddWorkHeaderControl1.SavePhoto()

                'sql.AppendFormat("UPDATE WorkHeader set ")
                'sql.AppendFormat("UpdateDate=getdate() ")
                'If Me.AddWorkHeaderControl1.PreExecutionPhotoName <> "" Then
                '    sql.AppendFormat(",PreExecutionPhotoName = '{0}' ", Me.AddWorkHeaderControl1.PreExecutionPhotoName)
                'End If
                'If Me.AddWorkHeaderControl1.PostExecutionPhotoName <> "" Then
                '    sql.AppendFormat(",PostExecutionPhotoName = '{0}' ", Me.AddWorkHeaderControl1.PostExecutionPhotoName)
                'End If
                'sql.AppendFormat("WHERE WorkHeaderID = '{0}';", Me.WorkHeaderID)
            End If
            'If DataAccessMode = FormDataAccessMode.Take OrElse DataAccessMode = FormDataAccessMode.Approve Then

            '    GridView_Volunteers.AllowPaging = False
            '    GridView_Volunteers.DataBind()
            'End If

            For Each gvr As GridViewRow In GridView_Volunteers.Rows

                'Dim cblCheckStatus As CheckBoxList = gvr.FindControl("cblCheckStatus")
                Dim chkSignIn As CheckBox = TryCast(gvr.FindControl("chkSignIn"), CheckBox)
                Dim chkSignOut As CheckBox = TryCast(gvr.FindControl("chkSignOut"), CheckBox)

                i = 0

                If chkSignIn.Checked = True Then
                    i += 1
                End If

                If chkSignOut.Checked = True Then
                    i += 2
                End If

                Dim strFlag As String = "N"

                If i >= 3 Then
                    strFlag = "Y"
                Else
                    strFlag = "N"
                End If

                If DataAccessMode = FormDataAccessMode.Take Then

                    sql.AppendFormat("UPDATE WorkRecord SET Status={0} WHERE RecordID={1};", i, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                    sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}',CreateDate=getdate() WHERE RecordID={1} and WorkType='CleanPlan';", "N", GridView_Volunteers.DataKeys(gvr.RowIndex).Value)

                Else

                    sql.AppendFormat("UPDATE WorkRecord SET Status={0},UpdateDate=getdate() WHERE RecordID={1};", i, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)

                    Dim active As String

                    If strFlag = "Y" And Me.Approved = True Then
                        active = "Y"
                    Else
                        active = "N"
                    End If

                    '第一次審核記錄時數生效日期
                    If active = "N" Then
                        sql.AppendFormat("UPDATE WorkHourRecord SET UpdateDate = getdate(),Updateby= '{0}' where RecordID={1} and Active = 'N' ", clsAuth.GetUserID(), GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                    End If
                    sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}' WHERE RecordID={1} and WorkType='CleanPlan';", active, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                    If active = "Y" Then
                        sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate(),EffectiveBy = '{0}' where RecordID={1} and WorkType='CleanPlan'; ", clsAuth.GetUserID(), GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                    End If

                End If


            Next

            'If DataAccessMode = FormDataAccessMode.Take OrElse DataAccessMode = FormDataAccessMode.Approve Then
            '    GridView_Volunteers.AllowPaging = True
            '    GridView_Volunteers.DataBind()
            'End If


            If sql.Length <> 0 Then
                dat.AccData(sql)
                'MyObj.WriteLog(clsAuth.GetUserID() & "," & Now.ToString() & "," & MyObj.getIP() & "," & sql.ToString())
                MyObj.ShowMessage(Me.GetLocalResourceObject("SaveOK"))
                'If Me.DataAccessMode = FormDataAccessMode.Take OrElse (Me.DataAccessMode = FormDataAccessMode.Execute And Me.Approved = False) Then
                '    btnSave.Enabled = False
                'End If
            End If

            scope.Complete()

        End Using

        RaiseEvent Save_Click(Me, New EventArgs)

    End Sub

    Public Function EcolifeInsert(ByVal EcolifeCaseNo As String) As String
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As DataTable

        Dim i As Integer

        Dim MyWorkHeaderID As Integer

        sql.AppendFormat("select a.WorkHeaderID from WorkHeader a join CleanPlanMapping b ")
        sql.AppendFormat("on a.WorkHeaderID=b.WorkHeaderID ")
        sql.AppendFormat("where b.PlanID='{0}' ", Me.PlanID)
        sql.AppendFormat("and a.EcolifeCaseNo='{0}' ", EcolifeCaseNo)
        dt = dat.GetData(sql.ToString())

        If dt.Rows.Count > 0 Then
            MyWorkHeaderID = dt.Rows(0)("WorkHeaderID")
            Me.WorkHeaderID = MyWorkHeaderID
        Else
            Using scope As New Transactions.TransactionScope
                sql.Length = 0

                '存檔-WorkHeader
                sql.AppendFormat("INSERT WorkHeader (CreateType,EcolifeCaseNo,UOrganizationID,VUOrganizationID,LeaderID,CreateDate,CreateBy,TakeDate,Active) ")
                sql.AppendFormat("SELECT 'P' ")
                sql.AppendFormat(",'{0}' ", EcolifeCaseNo)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.UOrganizationID)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.VOrganizationID)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.VolunteerID)

                sql.AppendFormat(", getdate()")
                sql.AppendFormat(", '{0}' ", Page.User.Identity.Name)
                sql.AppendFormat(", '{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                sql.AppendFormat(", '{0}'; ", "N")

                dat.AccData(sql)

                '將服務計畫加到某計畫底下
                sql.Length = 0

                'MyWorkHeaderID是local變數
                MyWorkHeaderID = MyObj.GetIdentity()
                Me.WorkHeaderID = MyObj.GetIdentity()

                sql.AppendFormat("INSERT CleanPlanMapping (PlanID,WorkHeaderID) ")
                sql.AppendFormat("SELECT '{0}',{1};", PlanID, MyWorkHeaderID)


                sql.AppendFormat("UPDATE WorkRecord ")
                sql.AppendFormat("SET WorkHeaderID = '{0}'", MyWorkHeaderID)
                sql.AppendFormat("WHERE WorkHeaderID = 0 and CreateBy='{0}';", Page.User.Identity.Name)


                sql.AppendFormat("UPDATE UploadFiles ")
                sql.AppendFormat("SET theType = '{0}'", MyWorkHeaderID)
                sql.AppendFormat("WHERE theType = '0' and CreateBy='{0}';", Page.User.Identity.Name)

                For Each gvr As GridViewRow In GridView_Volunteers.Rows
                    Dim chkSignIn As CheckBox = TryCast(gvr.FindControl("chkSignIn"), CheckBox)
                    Dim chkSignOut As CheckBox = TryCast(gvr.FindControl("chkSignOut"), CheckBox)

                    i = 0

                    If chkSignIn.Checked = True Then
                        i += 1
                    End If

                    If chkSignOut.Checked = True Then
                        i += 2
                    End If

                    Dim strFlag As String = "N"

                    If i >= 3 Then
                        strFlag = "Y"
                    Else
                        strFlag = "N"
                    End If

                    If DataAccessMode = FormDataAccessMode.Take Then

                        sql.AppendFormat("UPDATE WorkRecord SET Status={0} WHERE RecordID={1};", i, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                        sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}',CreateDate=getdate() WHERE RecordID={1} and WorkType='CleanPlan';", "N", GridView_Volunteers.DataKeys(gvr.RowIndex).Value)

                    Else

                        sql.AppendFormat("UPDATE WorkRecord SET Status={0},UpdateDate=getdate() WHERE RecordID={1};", i, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)

                        Dim active As String

                        If strFlag = "Y" And Me.Approved = True Then
                            active = "Y"
                        Else
                            active = "N"
                        End If

                        '第一次審核記錄時數生效日期
                        If active = "N" Then
                            sql.AppendFormat("UPDATE WorkHourRecord SET UpdateDate = getdate(),Updateby= '{0}' where RecordID={1} and Active = 'N' ", clsAuth.GetUserID(), GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                        End If
                        sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}' WHERE RecordID={1} and WorkType='CleanPlan';", active, GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                        If active = "Y" Then
                            sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate(),EffectiveBy = '{0}' where RecordID={1} and WorkType='CleanPlan'; ", clsAuth.GetUserID(), GridView_Volunteers.DataKeys(gvr.RowIndex).Value)
                        End If
                    End If


                Next

                If sql.Length <> 0 Then
                    dat.AccData(sql)
                End If

                'Ecolife資料自動帶入
                '==============================================================================
                '自動帶入清理時間
                sql.Length = 0
                sql.AppendFormat("select CleanDateStart,CleanDateEnd from EcolifeDataView ")
                sql.AppendFormat("where CaseNo='{0}'", EcolifeCaseNo)
                dt = dat.GetData(sql)
                If dt.Rows.Count > 0 Then
                    sql.Length = 0
                    sql.AppendFormat("update WorkHeader set ")
                    sql.AppendFormat("WorkStartDate='{0:yyyy/MM/dd HH:mm:ss}' ", dt.Rows(0)("CleanDateStart"))
                    sql.AppendFormat(",WorkEndDate='{0:yyyy/MM/dd HH:mm:ss}' ", dt.Rows(0)("CleanDateStart"))
                    sql.AppendFormat("where WorkHeaderID='{0}' ", MyWorkHeaderID)
                    dat.AccData(sql.ToString)
                End If

                '自動帶入通報物件
                sql.Length = 0
                sql.AppendFormat("select a.Count,b.TableName,b.Value from EcolifeItemView a ")
                sql.AppendFormat("join EcolifeItemMapping b ")
                sql.AppendFormat("on a.ItemName=b.ItemName ")
                sql.AppendFormat("where a.CaseNo='{0}'", EcolifeCaseNo)
                dt = dat.GetData(sql)

                If dt.Rows.Count > 0 Then
                    For j As Integer = 0 To dt.Rows.Count - 1
                        Dim dt2 As DataTable
                        sql.Length = 0
                        sql.AppendFormat("select a.Value as ItemID,b.Value as ItemGroupID from CodeMapping a ")
                        sql.AppendFormat("join CodeMapping b ")
                        sql.AppendFormat("on b.TableName+'_'+b.ColumnName+'_'+b.Value=a.TableName ")
                        sql.AppendFormat("where a.TableName='{0}' ", dt.Rows(i)("TableName"))
                        sql.AppendFormat("and a.Value='{0}' ", dt.Rows(i)("Value"))
                        dt2 = dat.GetData(sql)

                        If dt2.Rows.Count > 0 Then
                            sql.Length = 0
                            sql.AppendFormat("Insert workItem(WorkHeaderID,ItemGroupID,ItemID,Amount) ")
                            sql.AppendFormat("Select '{0}' ", MyWorkHeaderID)
                            sql.AppendFormat(",'{0}' ", dt2.Rows(0)("ItemGroupID").ToString)
                            sql.AppendFormat(",'{0}' ", dt2.Rows(0)("ItemID").ToString)
                            sql.AppendFormat(",'{0}';", dt.Rows(0)("Count").ToString())
                            dat.AccData(sql)
                        End If
                    Next
                End If
                '==============================================================================

                scope.Complete()

            End Using
        End If

        Return MyWorkHeaderID
    End Function

#End Region

#Region "DataBinding-將值分散"
    Protected Sub cblCheckStatus_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cblCheckStatus As CheckBoxList = sender
        Dim gvr As GridViewRow = cblCheckStatus.NamingContainer

        Dim CheckStatus As Integer = DataBinder.Eval(gvr.DataItem, "Status").ToString()

        Select Case CheckStatus
            Case 1
                cblCheckStatus.Items(0).Selected = True
                cblCheckStatus.Items(1).Selected = False
            Case 2
                cblCheckStatus.Items(0).Selected = False
                cblCheckStatus.Items(1).Selected = True
            Case 3
                cblCheckStatus.Items(0).Selected = True
                cblCheckStatus.Items(1).Selected = True
            Case Else
                cblCheckStatus.Items(0).Selected = False
                cblCheckStatus.Items(1).Selected = False
        End Select

    End Sub

#End Region

#Region "開窗取值-把選到的志工存值方法"
    Private Function SavePerson() As Boolean

        Dim dat As New clsData
        Dim sql As New MyStringBuilder
     
        Using scope As New Transactions.TransactionScope

    
            sql.Length = 0
            For Each VolunteerID As String In Me.SearchVolunteerControl_AddCleanPlan1.SelectedValues
                sql.AppendFormat("INSERT WorkRecord (WorkHeaderID,Status,CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT {0}", WorkHeaderID)
                sql.AppendFormat(", '{0}'", 0)
                sql.AppendFormat(", getdate()")
                sql.AppendFormat(", '{0}'; ", Me.Page.User.Identity.Name)

                sql.AppendFormat("INSERT WorkHourRecord (RecordID,WorkType,VolunteerID,WorkHour,WorkTimes,Active,CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT @@IDENTITY")
                sql.AppendFormat(", 'CleanPlan'")
                sql.AppendFormat(", '{0}'", VolunteerID)
                sql.AppendFormat(", '{0}'", txtDefaultWorkHour.Text)
                sql.AppendFormat(", '{0}'", txtDefaultWorkTimes.Text)
                sql.AppendFormat(", 'N'")

                If DataAccessMode = FormDataAccessMode.Take Then
                    sql.AppendFormat(", null")
                ElseIf DataAccessMode = FormDataAccessMode.Execute Or DataAccessMode = FormDataAccessMode.Approve Then
                    sql.AppendFormat(", getdate()")
                End If

                sql.AppendFormat(", '{0}'; ", Me.Page.User.Identity.Name)

            Next

            Try
                dat.AccData(sql)
            Catch ex As System.Exception
                MyObj.WriteErrorLog(sql.ToString())
            End Try



            scope.Complete()

        End Using

        Return True

    End Function
#End Region

#Region "匯出簽到表"
    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click



        Dim GV As New GridView
        Dim ResultDataTable As DataTable
        Dim dat As New clsData

        Dim sqlParams As SqlParameter() = New SqlParameter(0) {}

        sqlParams(0) = New SqlParameter("@WorkHeaderID", SqlDbType.Int)
        sqlParams(0).Value = WorkHeaderID

        ResultDataTable = dat.GetData("GetVolunteerRegisterTable_CleanPlanV2", sqlParams, CommandType.StoredProcedure, "ResultTable").Tables.Item(0)

        If ResultDataTable IsNot Nothing AndAlso ResultDataTable.Rows.Count > 0 Then
            'Prepare Data

            Dim base As Integer = 15

            Dim vList As New List(Of CleanPlan)
            Dim v As CleanPlan



            Dim i As Integer = 1
            Dim VOrg As String

            For Each dr As DataRow In ResultDataTable.Rows
                If VOrg <> "" AndAlso VOrg <> dr("VOrganizationName") Then

                    For j As Integer = (i Mod base) To base
                        v = New CleanPlan
                        v.Name = ""
                        v.VOrganizationName = ""
                        v.Index = i
                        vList.Add(v)

                        i = i + 1
                    Next

                    i = 1
                End If

                v = New CleanPlan
                v.Name = dr("VolunteerName").ToString()
                v.VOrganizationName = dr("VOrganizationName").ToString()
                '
                v.Index = i
                vList.Add(v)

                If i Mod base = 1 Then
                    v.IsHeader = True
                Else
                    v.IsHeader = False
                End If

                i += 1
                If Not TypeOf dr("VOrganizationName") Is DBNull Then
                    VOrg = dr("VOrganizationName")
                Else
                    VOrg = ""
                End If

            Next

            For j As Integer = (i Mod base) To base
                v = New CleanPlan
                v.Name = ""
                v.VOrganizationName = ""
                v.Index = i
                vList.Add(v)

                i = i + 1
            Next

            'Print

            Dim fileName As String = "CleanPlan.xls"
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
            Response.ContentType = "application/vnd.ms-excel"

            Dim velocity As New VelocityEngine
            Dim props As New Commons.Collections.ExtendedProperties

            'fix bug
            props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
            props.AddProperty("input.encoding", "utf-8")
            props.AddProperty("output.encoding", "utf-8")
            velocity.Init(props)

            Dim template As Template

            Dim context As New VelocityContext

            template = velocity.GetTemplate("服務時數簽到表v2.xml")

            'context.Put("StartYear", DateTime.Parse(ResultDataTable.Rows.Item(0).Item("TakeDate")).Year - 1911)
            'context.Put("StartDate", DateTime.Parse(ResultDataTable.Rows.Item(0).Item("TakeDate")).ToString("MM/dd"))
            context.Put("OrganizationName", TryCast(fv.FindControl("txtOrganizationName"), TextBox).Text.Trim())
            context.Put("LeaderName", Me.AddLeader1.LeaderName)
            context.Put("LeaderOrg", Me.AddLeader1.VOrgName)
            context.Put("Phone", Me.AddLeader1.Phone)
            context.Put("PlanName", TryCast(fv.FindControl("txtPlanName"), TextBox).Text.Trim())
            context.Put("PrintRowCount", vList.Count + 5)
            context.Put("VolunteerList", vList)
            context.Put("User", clsAuth.GetUserID())
            context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
            context.Put("IP", MyObj.getIP())
            Dim writer As New IO.StringWriter
            template.Merge(context, writer)

            Response.Write(writer.GetStringBuilder().ToString())

            Response.End()


        Else

            MyObj.ShowMessage(Me.GetLocalResourceObject("NoData"))

        End If
    End Sub

    Public Class CleanPlan
        Private NameField As String
        Private VOrganizationNameField As String
        Private IndexField As Integer
        Private IsHeaderField As Boolean

        Public Property Name() As String
            Get
                Return Me.NameField
            End Get
            Set(ByVal value As String)
                Me.NameField = value
            End Set
        End Property

        Public Property VOrganizationName() As String
            Get
                Return Me.VOrganizationNameField
            End Get
            Set(ByVal value As String)
                Me.VOrganizationNameField = value
            End Set
        End Property



        Public WriteOnly Property IsHeader() As Boolean
            Set(ByVal value As Boolean)
                Me.IsHeaderField = value
            End Set
        End Property

        Public ReadOnly Property CellText() As String
            Get
                If Me.IsHeaderField = True Then
                    Return "<Cell ss:MergeDown=""15"" ss:StyleID=""s52""><Data ss:Type=""String""></Data><NamedCell ss:Name=""Print_Area""/></Cell>"
                Else
                    Return ""
                End If
            End Get
        End Property

        Public ReadOnly Property CellText2() As String
            Get
                If Me.IsHeaderField = True Then
                    Return ""
                Else
                    Return "ss:Index=""2"""
                End If
            End Get
        End Property

        Public Property Index() As Integer
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As Integer)
                Me.IndexField = value
            End Set
        End Property

        Private RegStatusField As String

        Public Property RegStatus() As String
            Get
                Return Me.RegStatusField
            End Get
            Set(ByVal value As String)
                Me.RegStatusField = value
            End Set
        End Property

    End Class
#End Region

#Region "刪除"

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        Dim SaveRecordID As New List(Of String)
        For Each row As GridViewRow In Me.GridView_Volunteers.Rows
            Dim key As DataKey = Me.GridView_Volunteers.DataKeys(row.RowIndex)
            If TryCast(row.FindControl("chkdelete"), CheckBox).Checked = True Then
                SaveRecordID.Add(key("RecordID"))
            End If
        Next

        If SaveRecordID.Count > 0 Then
            Dim RecordIDString As String = ""
            RecordIDString = Regex.Replace(String.Join(",", SaveRecordID.ToArray()), "(\d+)", "'$1'")
            sql.Length = 0
            sql.AppendFormat("Delete from WorkRecord where RecordID in ({0}); ", RecordIDString)
            sql.AppendFormat("Delete from WorkHourRecord where RecordID in ({0}); ", RecordIDString)
            dat.AccData(sql)
            MyObj.ShowMessage("刪除成功!")
            Me.BindGV()
        Else
            MyObj.ShowMessage("您沒有勾選任何要刪除的資料!!")
        End If
    End Sub
#End Region

#Region "更新"
    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.Length = 0
        For Each row As GridViewRow In Me.GridView_Volunteers.Rows
            Dim key As DataKey = Me.GridView_Volunteers.DataKeys(row.RowIndex)
            sql.AppendFormat("Update WorkHourRecord Set ")
            sql.AppendFormat("WorkHour='{0}' ", TryCast(row.FindControl("txtWorkHour"), TextBox).Text.Trim())
            sql.AppendFormat("where RecordID ='{0}'; ", key("RecordID"))
        Next

        dat.AccData(sql)
        MyObj.ShowMessage("更新成功!")
        Me.BindGV()
    End Sub
#End Region
End Class

Partial Class WebForm_ManageWorkRecord_AddCleanPlan
    Dim wrManager As New WorkRecordManager
    Public Sub InitData(ByVal intPlanID As Integer, ByVal intWorkHeaderID As Integer)

        PlanID = intPlanID
        WorkHeaderID = intWorkHeaderID



        Me.plButtonList.Visible = True
        Me.AddWorkHeaderControl1.ValidationGroup = ""

        If intPlanID = 0 Then
            '新增
            Me.DataAccessMode = FormDataAccessMode.Insert
            AddLeader1.InitData(0)
            Me.plCleanResult.Visible = False
            txtPlanName.Text = String.Empty
            Me.btnApprove.Visible = False
        ElseIf WorkHeaderID = 0 Then
            '認養

            Me.DataAccessMode = FormDataAccessMode.Take
            AddLeader1.InitData(WorkHeaderID)
            Me.plCleanResult.Visible = False
            Me.BindFV()
            Me.BindGV()
            txtPlanName.Text = TryCast(Me.fv.FindControl("txtPlanName"), TextBox).Text
            Me.btnApprove.Visible = False
            Me.lblTotal.Text = ""
            Me.btnSave.Visible = True
            Me.btnUpdate.Visible = False
        Else
            '編輯
            'Me.DataAccessMode = FormDataAccessMode.Execute

            If Me.DataAccessMode = FormDataAccessMode.View Then
                Me.plButtonList.Visible = False
            End If
            'Me.btnSign.Visible = False
            Me.plCleanResult.Visible = True
            Me.AddWorkHeaderControl1.ValidationGroup = Me.ValidationGroup
            AddWorkHeaderControl1.DataAccessMode = FormViewMode.Edit
            AddWorkHeaderControl1.InitData(WorkHeaderID)
            AddLeader1.InitData(WorkHeaderID)

            Me.BindFV()

            AddWorkHeaderControl1.PlanID = Me.fv.DataKey("PlanID").ToString()
            txtPlanName.Text = TryCast(Me.fv.FindControl("txtPlanName"), TextBox).Text

            '繫結清潔內容的資料
            'Me.AddWorkItemControl1.BindWorkItemForEdit(Me.WorkHeaderID)

       
            If Me.CanAdmin = True OrElse Me.CanEdit = True Then
                Me.btnApprove.Visible = True
                Me.btnSave.Visible = False
            Else
                Me.btnApprove.Visible = False
                Me.btnSave.Visible = True
            End If
            Me.btnUpdate.Visible = True
            Me.BindGV()
        End If


        UploadFileControl1.strType = WorkHeaderID
  
        txtDefaultWorkHour.Text = "0"
        txtDefaultWorkTimes.Text = "1"

        VolunteerQueryControl1.IsVolunteerLeader = IIf(Me.CanAdmin = False And Me.CanQuery = True, True, False)
        VolunteerQueryControl1.InitData()

    End Sub
    Public Sub BindGV()
        Dim dt As DataTable = wrManager.AddCleanGetData(WorkHeaderID, VolunteerQueryControl1.OrganizationID, VolunteerQueryControl1.VOrganizationID, VolunteerQueryControl1.VolunteerId, VolunteerQueryControl1.VolunteerName, VolunteerQueryControl1.VolunteerTEL)
        Dim Count As Integer = dt.Rows.Count

        Me.lblTotal.Text = IIf(Count > 0, Count & Space(1) & "records", "")
        GridView_Volunteers.DataSource = dt
        GridView_Volunteers.DataBind()
    End Sub
    Public Sub BindFV()
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        '取得PlanName
        sql.Length = 0

        sql.AppendFormat("Select c.PlanID,c.RegionType,c.IsPublic,c.PlanName,c.UOrganizationID,c.PersonInCharge ")
        sql.AppendFormat(",c.OrganizationTel,c.Location,c.StartDate,c.EndDate ")
        sql.AppendFormat(",o.OrganizationName ")
        sql.AppendFormat("From CleanPlan c Left Outer join OrganizationView o ")
        sql.AppendFormat("on c.UOrganizationID = o.UOrganizationID ")
        sql.AppendFormat("Where c.PlanID='{0}'", PlanID)

        Dim dtResult As DataTable = dat.GetData(sql)

        If (dtResult IsNot Nothing AndAlso dtResult.Rows.Count > 0) Then

            Me.fv.ChangeMode(FormViewMode.Edit)
            Me.fv.DataSource = dtResult
            Me.fv.DataBind()

        End If
    End Sub

#Region "Property"

    Public Property DataAccessMode() As FormDataAccessMode
        Get
            Return ViewState("DataAccessMode")
        End Get
        Set(ByVal value As FormDataAccessMode)
            ViewState("DataAccessMode") = value
        End Set
    End Property

    Public Property PlanID() As Integer
        Get
            Return ViewState("PlanID")
        End Get
        Set(ByVal value As Integer)
            ViewState("PlanID") = value
        End Set
    End Property

    Public Property WorkHeaderID() As Integer
        Get
            Return ViewState("WorkHeaderID")
        End Get
        Set(ByVal value As Integer)
            ViewState("WorkHeaderID") = value
        End Set
    End Property

    Public Property UOrganizationID() As String
        Get
            Return ViewState("UOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("UOrganizationID") = value
        End Set
    End Property

    Public Property VOrganizationID() As String
        Get
            Return ViewState("VOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("VOrganizationID") = value
        End Set
    End Property
    Public Property Approved() As Boolean
        Get
            If ViewState("Approved") Is Nothing Then
                ViewState("Approved") = False
            End If

            Return ViewState("Approved")
        End Get
        Set(ByVal value As Boolean)
            ViewState("Approved") = value
        End Set
    End Property

    Public ReadOnly Property ValidationGroup() As String
        Get
            Return "AddWorkHeaderA"
        End Get
    End Property
#End Region

End Class

Public Enum FormDataAccessMode
    Insert
    Take
    Execute
    Approve
    View
End Enum